const mysql = require('mysql2/promise');

async function setTimestampDefaults() {
    const connection = await mysql.createConnection({
        host: process.env.DB_HOST || '43.143.253.188',
        user: process.env.DB_USER || 'nextjs',
        password: process.env.DB_PASS || 'yEAiRE2jcxTyRBy5',
        database: process.env.DB_NAME || 'nextjs'
    });

    try {
        console.log('🔧 为MySQL 5.5数据库设置时间戳默认值...');

        // 获取所有表名
        const [tables] = await connection.execute('SHOW TABLES');
        console.log(`📋 找到 ${tables.length} 个表`);

        for (const table of tables) {
            const tableName = Object.values(table)[0];
            console.log(`\n🔍 处理表: ${tableName}`);

            // 检查表是否有created_at和updated_at字段
            const [columns] = await connection.execute(`SHOW COLUMNS FROM ${tableName}`);
            const hasCreatedAt = columns.some(col => col.Field === 'created_at');
            const hasUpdatedAt = columns.some(col => col.Field === 'updated_at');

            if (!hasCreatedAt && !hasUpdatedAt) {
                console.log(`⏭️ 跳过表 ${tableName}（没有时间戳字段）`);
                continue;
            }

            // 修改created_at字段，添加默认值
            if (hasCreatedAt) {
                try {
                    await connection.execute(`
            ALTER TABLE ${tableName} 
            MODIFY COLUMN created_at DATETIME NOT NULL DEFAULT '1970-01-01 00:00:00' COMMENT '创建时间'
          `);
                    console.log(`✅ 更新created_at字段: ${tableName}`);
                } catch (error) {
                    console.log(`❌ 更新created_at字段失败: ${error.message}`);
                }
            }

            // 修改updated_at字段，添加默认值
            if (hasUpdatedAt) {
                try {
                    await connection.execute(`
            ALTER TABLE ${tableName} 
            MODIFY COLUMN updated_at DATETIME NULL DEFAULT NULL COMMENT '更新时间'
          `);
                    console.log(`✅ 更新updated_at字段: ${tableName}`);
                } catch (error) {
                    console.log(`❌ 更新updated_at字段失败: ${error.message}`);
                }
            }
        }

        console.log('\n🎉 所有表的时间戳字段默认值设置完成！');

    } catch (error) {
        console.error('❌ 设置时间戳默认值时出错:', error);
    } finally {
        await connection.end();
    }
}

// 运行脚本
setTimestampDefaults().catch(console.error);
